<?php

declare(strict_types=1);

namespace App\Model;

use App\Overwrites\MineModel;
use App\Utils\WechatMiniApp;
use Throwable;

/**
 * @property int $id 
 * @property string $name 名称
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 */
class Channel extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'channels';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'name', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public bool $incrementing = false;

    protected function getUrlAttribute(): string
    {
        try {
            $file = sprintf('channel/%s.png', $this->id);
            $filename = sprintf('%s/public/%s', BASE_PATH, $file);
            if (!file_exists($filename)) {
                (new WechatMiniApp())->getUnlimitedQRCode((string)$this->id, $filename);
            }
            return sprintf('%s/%s', config('file.storage.local.url'), $file);
        } catch (Throwable $e) {
            return '';
        }
    }
}
